package team.kas.anime.service.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import team.kas.anime.dao.UserMapper;
import team.kas.anime.pojo.Result;
import team.kas.anime.pojo.User;
import team.kas.anime.service.UserService;
import team.kas.anime.util.ImgUpUtils;
import team.kas.anime.util.Sendsms;
import team.kas.anime.util.UpUtils;
import team.kas.anime.util.Md5Util;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     *登录验证方法
     */
    @Override
    public Result login(String remember, String username, String password, String code, HttpServletRequest request) {
        Result result = new Result();
        String newCode = (String)request.getSession().getAttribute("code");
        if(newCode.equalsIgnoreCase(code)){
            User user = userMapper.selectByUsername(username);
            String pwd = Md5Util.encryption(username,password);
            if(user != null && pwd.equals(user.getPassword())){
                request.getSession().setAttribute("user",user);
                if(remember != null){
                    request.getSession().setMaxInactiveInterval(24*60*60);
                }
                return result;
            }else{
                result.setCode(500);
                result.setMsg("用户名或密码错误！");
                return result;
            }
        }else{
            result.setCode(500);
            result.setMsg("验证码错误！");
            return result;
        }
    }

    @Override
    public Result verifyUsername(String username) {

        Result result = new Result();
        User user = userMapper.selectByUsername(username);
        if(user != null){
            result.setCode(500);
            result.setMsg("用户名重复");
            return result;
        }else{
            return result;
        }
    }

    @Override
    public Result mobileCode(String phone, HttpServletRequest request) {
        Result result = new Result();
        Result sms = Sendsms.sms(phone);
        if(sms.getCode() == 2){
            Integer mobileCode = sms.getCount();
            request.getSession().setAttribute("mobileCode",mobileCode);
            request.getSession().setMaxInactiveInterval(600);
            result.setMsg(sms.getMsg());
            return result;
        }else {
            result.setCode(sms.getCode());
            result.setMsg(sms.getMsg());
            return result;
        }
    }

    @Override
    public Result upImg(MultipartFile file, HttpServletRequest request) {

        String type = "user";
        Result result = new Result();
        try {
            UpUtils.upfile(file,request,type);
            String imgName = file.getOriginalFilename();
            result.setMsg(imgName);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("上传失败！");
            return result;
        }
    }

    @Override
    public Result register(User user) {

        Result result = new Result();
        try {
            String id = UUID.randomUUID().toString();
            String password = Md5Util.encryption(user.getUsername(),user.getPassword());
            user.setPassword(password);
            String imgPath = "/img/userImg/" + user.getFaceImage();
            User newUser = new User(id,user.getUsername(),password,imgPath,user.getNickname(),0,0,user.getIphone(),0,"1");
            userMapper.insert(newUser);
            result.setMsg("注册成功");
            return result;
        }catch (Exception e){
            result.setCode(500);
            result.setMsg("系统繁忙，请稍后重试！");
            return result;
        }
    }
    @Override
    public Result selectByLike(String value, Integer page, Integer limit) {
        Result result=new Result();
        Integer start=(page-1)*limit;
        List<User> users=userMapper.selectByLike(value,start,limit);
        result.setCount(users.size());
        result.setData(users);
        return result;
    }

    @Override
//    分页查询
    public Result userlist(Integer page,Integer limit) {
        Integer startpostion=(page-1)*limit;
        Result result=new Result();
        List<User> user= userMapper.selectByPage(startpostion,limit);
        String img=userMapper.selectimg(1);
        Integer count=userMapper.selectcount();
        if (count==null)
        {
            result.setCode(500);
            result.setMsg("请检查数据库是否有值");
        }else{
            result.setData(user);
            result.setCount(count);
            result.setMsg("查询成功");
        }

        return result;
    }

    @Override
    public Result deleteBykey(String id) {
        Result result=new Result();
        if (id!=null){
            userMapper.deleteByPrimaryKey(id);
            result.setMsg("删除成功");
        }
        else {
            result.setCode(500);
            result.setMsg("系统繁忙！请联系超级管理员");
        }
        return result;
    }

    @Override
    public Result bulkdelete(String[] ids) {
        Result result=new Result();
        if (ids == null){
            result.setCode(404);
            result.setMsg("请选中至少一行");
        }
        else {
            userMapper.deleteBulk(ids);
            result.setMsg("删除成功");
        }
        return result;
    }

    @Override
    public User selectById(String id) {
        User user=userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public Result update(String id, String value, String field) {
        Result result=new Result();
        try {
            userMapper.update(id,value,field);
            result.setMsg("修改成功");
            return result;
        }catch (Exception e){
            e.printStackTrace();//控制台打印error
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
            result.setMsg("更新失败");
            result.setCode(500);
            return result;

        }
    }

    @Override
    public Result adduser(User user) {
        Result result=new Result();
        String id=Rom();
        user.setId(id);
        String pw = Md5Util.encryption(user.getUsername(),user.getPassword());//使用md5对密码进行加密
        user.setPassword(pw);
        userMapper.insert(user);
        result.setCode(0);
        result.setMsg("插入成功");
        return result;
    }

    @Override
    public Result imgupload(MultipartFile file, HttpServletRequest request) {
        Result result=new Result();
        try {
            ImgUpUtils.upImgfile(file,request);
            String filename=file.getOriginalFilename();
            result.setMsg(filename);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            result.setCode(500);
        }
        return result;
    }

    public String Rom(){//随机生成一个六位数的id
        String id= String.valueOf((int)(Math.random()*100000)+100000);
        if (userMapper.count(id)==0){
            return id;
        }
        else {
            return Rom();
        }
    }
}
